package com.mvwchina.common.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AES {
    private static final String IV = "+1A-2B?3C!4E~5F_";

    private static final String publicKey = "MVW_Boot_AES_PublicKey_JS_Secret";

    public AES() {
    }

    public static String encrypt(String plainText) throws Exception {
        return encrypt(plainText,publicKey);
    }

    public static String encrypt(String plainText, String publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        int blockSize = cipher.getBlockSize();
        byte[] dataBytes = plainText.getBytes("UTF-8");
        int plaintextLength = dataBytes.length;
        if (plaintextLength % blockSize != 0) {
            plaintextLength += blockSize - plaintextLength % blockSize;
        }

        byte[] plaintext = new byte[plaintextLength];
        System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
        SecretKeySpec keyspec = new SecretKeySpec(publicKey.getBytes("UTF-8"), "AES");
        IvParameterSpec ivspec = new IvParameterSpec("+1A-2B?3C!4E~5F_".getBytes("UTF-8"));
        cipher.init(1, keyspec, ivspec);
        byte[] encrypted = cipher.doFinal(plaintext);
        return (new BASE64Encoder()).encode(encrypted);
    }

    public static String decrypt(String cipherText) throws Exception{
        return decrypt(cipherText,publicKey);
    }

    public static String decrypt(String cipherText, String publicKey) throws Exception {
        byte[] encrypted = (new BASE64Decoder()).decodeBuffer(cipherText);
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        SecretKeySpec keyspec = new SecretKeySpec(publicKey.getBytes("UTF-8"), "AES");
        IvParameterSpec ivspec = new IvParameterSpec("+1A-2B?3C!4E~5F_".getBytes("UTF-8"));
        cipher.init(2, keyspec, ivspec);
        byte[] original = cipher.doFinal(encrypted);
        String originalString = new String(original);
        originalString = originalString.trim();
        return originalString;
    }
}